package net.rock.controller;

import net.rock.pojo.Order;
import net.rock.service.OrderService;
import net.rock.utils.ServiceCaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ServiceCaller serviceCaller;

    @PostMapping("/add")
    public void add(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Order order
    ) {
        int userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        order.setUserId(userId);
        orderService.add(order);
    }

    @PostMapping("/del")
    public void del(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Order order
    ) {
        // 保证用户已登陆, 理论上还要验证要删除的订单是否为该用户的订单, 但这里就不验证了
        int _userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        orderService.del(order.getId());
    }

    @PostMapping("/pay")
    public void pay(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Order order
    ) {
        // 保证用户已登陆, 理论上还要验证要支付的订单是否为该用户的订单, 但这里就不验证了
        int _userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        orderService.pay(order.getId());
    }

    @PostMapping("/confirm")
    public void confirm(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId,
            @RequestBody Order order
    ) {
        // 保证用户已登陆, 理论上还要验证要确认的订单是否为该用户的订单, 但这里就不验证了
        int _userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        orderService.confirm(order.getId());
    }

    @GetMapping("/fetch")
    public List<Order> fetch(
            @CookieValue(value = "sessionID", defaultValue = "") String sessionId
    ) {
        int userId = serviceCaller.fetchUserBySessionId(sessionId).getId();
        return orderService.fetchOrdersByUserId(userId);
    }
}
